<?php

namespace app\common\model;
use think\Model;

class Goods extends Model
{
    public function add($data)
    {
//        halt($data);die;
//        if(!isset($data['list_pic'])){
//            return $res = ['valid'=>2,'message'=>'请商品预览图'];
//        }
        #商品表goods
        $Goods          = new Goods();
        $Goods->title     = $data['title'] ;#商品名称
        $Goods->price    = $data['price'];#市场价
        $Goods->count    = $data['count'];#总库存
        $Goods->old_price    = $data['old_price'];#原价
        $Goods->description    = $data['description'];#商品描述
        $Goods->sex    = $data['sex'];#性别 1男 2女
        $Goods->list_pic    = $data['list_pic'];#列表页图
        $Goods->sale    = $data['sale'];#已售出
        $Goods->cid    = $data['cid'];#所属栏目
        $Goods->save();
        #商品属性表goods_attribute
        $data = json_decode($data['goods_attribute'],true);
        foreach($data as $v)
        {
            $GoodsAttribute = new Goodsattribute();
            $GoodsAttribute->color = $v['color'] ;
            $GoodsAttribute->repertory =$v['repertory'] ;#商品类型库存
            $GoodsAttribute->size = $v['size'];
            $GoodsAttribute->goods_id = $Goods->id ;
            $GoodsAttribute-> save();
            #商品图片表goods_pic
            foreach($v['pic'] as $k1=>$v1){
                $Goods_pic = new Goodspic();
                $Goods_pic->attributeid = $GoodsAttribute->id ;#关联商品属性表id
                $Goods_pic->pic = $v1;#图片路径
                $Goods_pic->gid = $Goods->id; #关联商品id
                $Goods_pic->save();
            }
        }
        return $res = ['valid'=>1,'message'=>'操作成功'];
    }

    /**
     * 关联
     * @return \think\model\relation\BelongsTo
     */
        public function category()
    {
        return $this->belongsTo('Category','cid');
    }
// ***************************前台***************************

    /**
     * 关联商品图片表(一对多)
     * @return \think\model\Relation
     */
        public function goods_pic()
        {
            return $this->hasMany('Goodspic','gid');
        }

    /**
     * 关联商品属性表(一对多)
     *
     */
         public function goods_attribute()
         {
             return $this-> hasMany('Goodsattribute','goods_id');
         }
}
